package com.china08.yxyapi.api.manage.sch.platform.live.lesson.up;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.live.YxyLiveLessonItem;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.live.YxyLiveLessonItemRepository;

@CrossOrigin
@RestController
public class LiveSchLessonUpdItemController extends YxyApiBaseController {

    @Autowired
    private YxyLiveLessonItemRepository yxyLiveLessonItemRepository;

    @RequestMapping(value = "/api_yw/manage/sch/platform/live/lesson/up/item/upd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response,
            @RequestBody(required = false) ReqModel reqModel) throws ParseException {

        YxyLiveLessonItem liveLessonItem = yxyLiveLessonItemRepository.findById(reqModel.itemId);

        liveLessonItem.setBeginDate(reqModel.bTime);
        liveLessonItem.setEndDate(reqModel.eTime);

        yxyLiveLessonItemRepository.save(liveLessonItem);

        // 重新排序
        List<YxyLiveLessonItem> findByLessonIdOrderByBeginDateAsc = yxyLiveLessonItemRepository
                .findByLessonIdOrderByBeginDateAsc(liveLessonItem.getLessonId());
        Integer num = 1;
        for (YxyLiveLessonItem yxyLiveLessonItem : findByLessonIdOrderByBeginDateAsc) {
            yxyLiveLessonItem.setItemNo(num);
            num++;
        }
        yxyLiveLessonItemRepository.save(findByLessonIdOrderByBeginDateAsc);

        RespModel model = new RespModel();
        model.setMessage("修改成功");
        return model;
    }

    public static class ReqModel extends YxyApiReqModel {
        // 课时ID
        public String itemId;
        // 开始时间
        public Date bTime;
        // 结束时间
        public Date eTime;

        @Override
        public void autoCheck() {
            Assert.isTrue(StringUtils.isNotBlank(itemId), "课时ID为空");
        }
    }

    public static class RespModel extends YxyApiRespModel {
    }

}
